﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EBA.Data
{
    /// <summary>
    /// 将<see cref="EntityCollection{TEntity}"/>包装为<see cref="ICollection{IEntity}"/>对象，解决数组的逆变和协变问题。
    /// </summary>
    public class EntityCollection<Entity, IEntity> : ICollection<IEntity> where Entity : class,IEntity
    {
        System.Data.Objects.DataClasses.EntityCollection<Entity> Items { get; set; }

        /// <summary>
        /// 构造函数。
        /// </summary>
        public EntityCollection(System.Data.Objects.DataClasses.EntityCollection<Entity> collections)
        {
            this.Items = collections??new System.Data.Objects.DataClasses.EntityCollection<Entity>();
        }

        /// <summary>
        /// 新增指定实例。
        /// </summary>
        public void Add(IEntity item)
        {
            this.Items.Add(item as Entity);
        }

        /// <summary>
        /// 清空所有实例。
        /// </summary>
        public void Clear()
        {
            this.Items.Clear();
        }

        /// <summary>
        /// 是否包含指定实例。
        /// </summary>
        public bool Contains(IEntity item)
        {
            return this.Items.Contains(item as Entity);
        }

        /// <summary>
        /// 拷贝指定实例到指定指定的数组。
        /// </summary>
        public void CopyTo(IEntity[] array, int arrayIndex)
        {
            this.Items.OfType<IEntity>().ToArray().CopyTo(array, arrayIndex);
        }

        /// <summary>
        /// 包含的实例数量。
        /// </summary>
        public int Count
        {
            get { return this.Items.Count; }
        }

        /// <summary>
        /// 集合是否只读。
        /// </summary>
        public bool IsReadOnly
        {
            get { return this.Items.IsReadOnly; }
        }

        /// <summary>
        /// 移除指定实例。
        /// </summary>
        public bool Remove(IEntity item)
        {
            return this.Items.Remove(item as Entity);
        }

        /// <summary>
        /// 返回集合迭代器。
        /// </summary>
        public IEnumerator<IEntity> GetEnumerator()
        {
            return this.Items.OfType<IEntity>().GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.Items.GetEnumerator();
        }
    }
}
